'use strict';
const db = uniCloud.database();
const fs = require("fs");
exports.main = async (event, context) => {
	// 必传项
	// {
	// 	state:"look", //增删改查状态
	// 	databaseName:"repository" //数据库名称
	// }

	// 数据库名称
	let databaseName = event.databaseName
	let state = event.state
	let sort = event.sort || 'desc'
	delete event['databaseName'] //删除这个多余的状态  重新赋值之后将他删除
	delete event['state'] //删除这个多余的状态
	delete event['sort'] //删除这个多余的状态
	// 查询条件
	let parmse = event;

	let res = null; //创建返回值上下文

	if (state == 'add') {
		res = await db.collection(databaseName).add(parmse);
		return {
			code: 200,
			message: "操作成功"
		}
	} else if (state == 'update') {
		let _id = event._id
		delete parmse['_id'] //删除这个多余的状态
		res = await db.collection(databaseName).where({
			_id: _id
		}).update(parmse)

		return {
			code: 200,
			message: "操作成功"
		}
	} else if (state == 'look') {
		// 便利对象,给为空的查询条件全部删除
		for (let key in parmse) {
			console.log(parmse[key], "key", key)
			if (!parmse[key]) {
				delete parmse[key]
			} else {

				if (key != '_id' && key != 'queryId') {
					parmse[key] = new RegExp(parmse[key], 'g')
				} else {}

			}
		}
		// desc  降序
		// asc   升序
		let dataList = []
		let limit = 100; // 每次查询的数量
		let offset = 0; // 偏移量	

		let {
			total
		} = await db.collection(databaseName).where(db.command.or({
			...parmse
		})).count() //获取数据

		do {
			res = await db.collection(databaseName).where(db.command.or({
				...parmse
			})).orderBy('createTime', sort).skip(offset).limit(limit).get();
			dataList = dataList.concat(res.data); // 将查询到的数据添加到列表中	 
			offset += limit; // 更新偏移量
		} while (offset < total);

		// res = await db.collection(databaseName).where(db.command.or({
		// 	...parmse
		// })).orderBy('createTime', sort).get() //获取数据

		return {
			code: 200,
			message: "操作成功",
			data: dataList,
			total: total,
		}
	} else if (state == 'delete') {
		let res = await db.collection(databaseName).doc(parmse._id).remove()
		return {
			code: 200,
			message: "操作成功"
		}
	}

}